package com.itany.shop.factory;

import com.itany.shop.exception.ObjectFactoryErrorException;
import com.itany.shop.util.JDBCTemplate;
import com.itany.shop.util.ParameterUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Miss Chen
 * @version 1.0
 * @date 2024年08月14日14:02
 */
public class ObjectFactory {
    private static Map<String,Object> objs;
    static{
        objs=new HashMap<>();
        BufferedReader br=null;

        try {
            br=new BufferedReader(
                    new InputStreamReader(
                            ObjectFactory
                                    .class
                                    .getClassLoader()
                                    .getResourceAsStream("beans.properties"))
            );

            String line=null;
            while((line=br.readLine())!=null){
                if(!ParameterUtil.isNull(line)){
                    String[] arr=line.split("=");
                    String key=arr[0];
                    String value=arr[1];
                    objs.put(key,Class.forName(value).newInstance());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        }finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new ExceptionInInitializerError("释放资源出错");
                }
            }
        }
    }

    public static Object getObject(String key){
        Object obj=objs.get(key);
        if(null==obj){
            throw new ObjectFactoryErrorException("根据指定的key："+key+"在配置文件中没有对应的配置");
        }
        return obj;
    }

    public static void main(String[] args) {
        JDBCTemplate jdbcTemplate= (JDBCTemplate) ObjectFactory.getObject("jdbc");
        System.out.println(jdbcTemplate);


    }

}
